package com.buer.storage.common.utils;

import java.io.InputStream;
import java.sql.Blob;
import java.util.Date;
import java.util.UUID;
import java.util.Vector;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 *
 * @author jk
 */
public class StringUtil {

    /**
     * 获取一个字符串,null转换为空字符串
     *
     * @param src 源对象
     * @return 字符串
     */
    public static String getStr(Object src) {

        return getStr(src, -1);

    }

    /**
     * 获取一个一定长度的字符串,null转换为空字符串
     *
     * @param src    源对象
     * @param length 字符串长度
     * @return 字符串
     */
    public static String getStr(Object src, int length) {
        if (src == null) {
            return "";
        }

        if (src instanceof String) {
            return (String) src;
        }

        String value = String.valueOf(src);

        return value.length() > length && length != -1 ? value.substring(0, length) : value;

    }

    /**
     * 从Blob中获取字符串
     *
     * @param blob Blob对象
     * @return 字符串
     */
    public static String fromBlob(Blob blob) {
        if (blob == null) {
            return "";
        }
        // StringBuffer sb = new StringBuffer();
        try {

            byte[] array = new byte[1000];
            InputStream in = blob.getBinaryStream();

            /**
             * hjs 为了修改乱码的问题
             */
            // 保存每次读取的字节列表
            Vector v = new Vector();

            // 保存每次读取的字节长度
            Vector v1 = new Vector();
            int len = in.read(array, 0, 1000);

            // 保存所有字节的长度
            int alllen = 0;
            while (len > 0) {
                // sb.append(new String(array, 0, len));
                alllen = alllen + len;
                v.add(array);
                v1.add(new Integer(len));
                array = new byte[1000];
                len = in.read(array, 0, 1000);
            }
            if (alllen > 0 && v.size() > 0) {
                byte[] arraytemp = new byte[alllen];
                int index = 0;
                for (int i = 0; i < v.size(); i++) {
                    int lentemp = ((Integer) v1.get(i)).intValue();
                    byte[] arraytt = (byte[]) v.get(i);
                    System.arraycopy(arraytt, 0, arraytemp, index, lentemp);
                    index = index + lentemp;
                }
                return new String(arraytemp);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * add by dkw
     * 20071107
     * 截取宽度固定字符串，若字符串宽度大于参数设置，则按照参数截取加上"..."
     *
     * @param string     待截取字符串
     * @param startIndex 截取开始位置
     * @param width      宽度（一个汉字宽度为宽度单位）
     * @return 截取后的字符串
     */
    public static String getWidthFixedStr(String string, int startIndex, int width, boolean htmlStr) {
        if (string == null || string.equals(""))
            return "";
        if (startIndex < 0)
            return "";
        if (width < 0)
            return "";

        char baseChar = ' '; // char = 32
        char topChar = '~'; // char = 126
        char c;
        double tempWidth = 0.0;
        int charIndex = 0;
        string = string.substring(startIndex);
        StringBuffer sb = new StringBuffer();
        String resultStr;

        string = string.replaceAll("&lt;", "<");
        string = string.replaceAll("&gt;", ">");
        string = string.replaceAll("&nbsp;", " ");
        string = string.replaceAll("&quot;", "\"");

        while (charIndex <= string.length() - 1 && tempWidth <= width - 1) {
            c = string.charAt(charIndex);
            if (c >= baseChar && c <= topChar)
                tempWidth += 0.5;
            else
                tempWidth += 1; // 汉字加1
            sb.append(c);
            charIndex++;
        }
        resultStr = sb.toString();
        if (resultStr.length() < string.length()) {
            sb.deleteCharAt(resultStr.length() - 1);
            sb.append("...");
            resultStr = sb.toString();
        }
        if (htmlStr) {
            resultStr = resultStr.replaceAll("<", "&lt;");
            resultStr = resultStr.replaceAll(">", "&gt;");
            resultStr = resultStr.replaceAll(" ", "&nbsp;");
            resultStr = resultStr.replaceAll("\"", "&quot;");
        }
        return resultStr;
    }

    /**
     * 把字符串中的回车符转换成指定的字符
     *
     * @param str     字符串
     * @param wrapStr 替换字符串
     * @return 字符串
     */
    public final static String transWrapToString(String str, String wrapStr) {
        StringBuffer sb = new StringBuffer(str);
        int notCheckedLength = sb.length();
        int start = 0;
        int wrapCount = WRAP.length;
        for (int j = 0; j < wrapCount; j++) {
            notCheckedLength = sb.length();
            start = 0;
            while (notCheckedLength > 0) {
                String temp = sb.substring(start);
                int index = temp.indexOf(WRAP[j]);
                if (index == -1) {
                    break;
                }

                notCheckedLength -= (index + WRAP[j].length());
                start += index;
                sb.replace(start, start + WRAP[j].length(), wrapStr);
                start += wrapStr.length();
            }
        }
        return sb.toString();
    }

    /**
     * 过滤文本编辑器里的 html标签 转化为纯文本
     *
     * @param inputString 文本编辑器里的文本
     * @return 返回没有html标签的文本 (纯文本)
     */
    public final static String html2Text(String inputString) {
        String htmlStr = inputString; //含html标签的字符串
        String textStr = "";
        Pattern p_script;
        java.util.regex.Matcher m_script;
        Pattern p_style;
        java.util.regex.Matcher m_style;
        Pattern p_html;
        java.util.regex.Matcher m_html;

        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script>]*?>[\\s\\S]*?<\\/script> }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style>]*?>[\\s\\S]*?<\\/style> }
            String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式

            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); //过滤script标签

            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); //过滤style标签

            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); //过滤html标签

            textStr = htmlStr;

            textStr = textStr.replaceAll(" ", "");
            textStr = textStr.replaceAll("&nbsp;", " ");
        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }

        return textStr;//返回文本字符串
    }

    private final static String WRAP[] = {"\r\n", "\r", "\n"}; // wrap
    private static int a=0;
    public static String generalKeyword() {
        String objectname = "ZH_OPERATE";//项目名
        String dateStr = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS");
        a = (int)((Math.random()*9+1)*10000);//产生1000-9999的随机数
        String restr = objectname + "-" + dateStr + "-" + String.valueOf(a);
        return restr;
    }

    public static String generalId() {
        String s = UUID.randomUUID().toString();
        String s1 = s.replaceAll("-", "");
        return s1;
    }

    public static String getOrderNo() {
            String objectname = "SC";// SC
        String dateStr = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS");
        a = (int)((Math.random()*9+1)*10000);//产生1000-9999的随机数
        String restr = objectname + "-" + dateStr + "-" + String.valueOf(a);
        return restr;
    }

    public static boolean isEmpty(String s){
        if(s==null||s.equals("")||s.equals("null")){
            return true;
        }
        return false;
    }
}
